package no.nordicsemi.support.v18.scanner;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.agp.components.Clock;
import ohos.app.Context;
import ohos.event.intentagent.IntentAgent;
import org.jetbrains.annotations.Nullable;

import java.security.Provider;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/* package */ class PendingIntentExecutor extends ScanCallback {
    private final IntentAgent callbackIntent;

    @Nullable
    private Context context;

    @Nullable
    private Context service;
    private long lastBatchTimestamp;
    private long reportDelay;
    PendingIntentExecutor(final IntentAgent callbackIntent,
                          final ScanSettings settings, ScannerService scannerService) {
        this.callbackIntent = callbackIntent;
        this.reportDelay = settings.getReportDelayMillis();
    }
    /* package */ void setTemporaryContext(@Nullable final Context context) {
        this.context = context;
    }
    public void onScanResult(final int callbackType, final ScanResult result) {
        final Context context = this.context != null ? this.context : this.service;
        if (context == null)
            return;
        final Intent extrasIntent = new Intent();
        extrasIntent.setParam(BluetoothLeScannerCompat.EXTRA_CALLBACK_TYPE, callbackType);
        extrasIntent.setSequenceableArrayListParam(BluetoothLeScannerCompat.EXTRA_LIST_SCAN_RESULT, new ArrayList<>(Collections.singletonList(result)));
        callbackIntent.equals(extrasIntent);
    }

    @Override
    public void onBatchScanResults(final List<ScanResult> results) {
        final Context context = this.context != null ? this.context : this.service;
        if (context == null)
            return;
        Clock clock = new Clock(context);
        final long now = clock.getTime();
        if (lastBatchTimestamp > now - reportDelay + 5) {
            return;
        }
        lastBatchTimestamp = now;
        final Intent extrasIntent = new Intent();
        final IntentParams Intent = new IntentParams();
        extrasIntent.setParam(BluetoothLeScannerCompat.EXTRA_CALLBACK_TYPE, ScanSettings.CALLBACK_TYPE_ALL_MATCHES);
        extrasIntent.setSequenceableArrayListParam(BluetoothLeScannerCompat.EXTRA_LIST_SCAN_RESULT, new ArrayList<>(results));
        Intent.setClassLoader(ScanResult.class.getClassLoader());
        callbackIntent.equals(extrasIntent);
    }

    @Override
    public void onScanFailed(final int errorCode) {
        final Context context = this.context != null ? this.context : this.service;
        if (context == null)
            return;
            final Intent extrasIntent = new Intent();
            extrasIntent.setParam(BluetoothLeScannerCompat.EXTRA_ERROR_CODE, errorCode);
            callbackIntent.equals(extrasIntent);
    }
}